/* eslint-disable */
const barcode = {
  barCodeType: (input) => {
    if (Object.prototype.toString.call(input) === '[object String]') {
      let prefix = input.substring(0, 1)
      let prefix2 = input.substring(0, 2).toUpperCase()
      let prefix4 = input.substring(0, 4)
      let prefix3 = input.substring(0, 3)

      if (prefix === "+") {
        return "HIBC"
      } else if (prefix === "(") {
        return "CODE128"
      } else if (((prefix3 === "012" || prefix2 === "FA") && (input.length == 24 || input.length == 23)) || (prefix2 === "F4" && input.length == 11)) {
        return "RFID"
      }
      //12.19add  通知单扫描（ASN开头）
      else if (input.indexOf("ASN") >= 0 || prefix2 === "AN"||input.indexOf("PO") >= 0) {
        return "ASN"
      } else if (prefix2 === "69" && input.length == 13) {
        return "NS"//国标
      } else if (prefix4 === "GTRK") {
        return "GTRK" //跟台入库包码
      } else if (prefix2 === "SN" || (prefix3 === "010" && input.length == 24) || (prefix === "G" && input.length == 11)) {
        return "SN" //
      }  else if (prefix2 === "JP" || (prefix3 === "010" && input.length == 24) || (prefix === "G" && input.length == 11)) {
        return "SN" //
      } else if (prefix2 === "RA" || prefix2 === "CA") {
        return "RA" //
      } else {
        return "GTIN"
      }
    }
  },
  gtinAnalysis: (input) => {
    let rules = [
      //编码规则，通过模板进行校验，运用贪婪模式获取最优解
      //01 10 17
      {
        pattern: /(01\d{13,14})(10.{1,20})(17\d{6})/igm,
        groupCount: 3,
        fields: ["gtin", "lot", "expiredDate"]
      },
      //01 17 10 91
      {
        pattern: /(01\d{13,14})(17\d{6})(10.{1,20})(91.{1,20})/igm,
        groupCount: 4,
        fields: ["gtin", "expiredDate", "lot", "sn"]
      },
      //01 10 17 21
      {
        pattern: /(01\d{13,14})(10.{1,20})(17\d{6})(21.{1,20})/igm,
        groupCount: 4,
        fields: ["gtin", "lot", "expiredDate", "sn"]
      },
      //01 17 11 21
      {
        pattern: /(01\d{13,14})(17\d{6})(11\d{6})(21.{1,20})/igm,
        groupCount: 4,
        fields: ["gtin", "expiredDate", "manufactureDate", "sn"]
      },
      //01 17 10
      {
        pattern: /(01\d{13,14})(17\d{6})(10.{1,20})/igm,
        groupCount: 3,
        fields: ["gtin", "expiredDate", "lot"]
      },
      //01 17  30* 10
      {
        pattern: /(01\d{13,14})(17\d{6})(30\d{1,8})(10.{1,22})/igm,
        groupCount: 5,
        fields: ["gtin", "expiredDate", "qty", "lot", "sn"]
      },
      //01 17 21
      {
        pattern: /(01\d{13,14})(17\d{6})(21.{1,20})/igm,
        groupCount: 3,
        fields: ["gtin", "expiredDate", "sn"]
      },
      //01 11 21
      {
        pattern: /(01\d{13,14})(11\d{6})(21.{1,20})/igm,
        groupCount: 3,
        fields: ["gtin", "manufactureDate", "sn"]
      },
      //01 10 17 11 21
      {
        pattern: /(01\d{13,14})(10.{1,20})(17\d{6})(11\d{6})(21.{1,20})/igm,
        groupCount: 5,
        fields: ["gtin", "lot", "expiredDate", "manufactureDate", "sn"]
      },
      //01 17 10 11 21
      {
        pattern: /(01\d{13,14})(17\d{6})(10.{1,20})(11\d{6})(21.{1,20})/igm,
        groupCount: 5,
        fields: ["gtin", "expiredDate", "lot", "manufactureDate", "sn"]
      },
      //01 10 11 21
      {
        pattern: /(01\d{13,14})(10.{1,20})(11\d{6})(21.{1,20})/igm,
        groupCount: 4,
        fields: ["gtin", "lot", "manufactureDate", "sn"]
      },
      //01 17* 21
      {
        pattern: /(01\d{13,14})(17.{12})(21.{1,20})/igm,
        groupCount: 3,
        fields: ["gtin", "expiredDate", "sn"]
      },
      //01 17* 11 21
      {
        pattern: /(01\d{13,14})(17.{12})(11\d{6})(21.{1,20})/igm,
        groupCount: 4,
        fields: ["gtin", "expiredDate", "manufactureDate", "sn"]
      },
      //01 17* 11* 21
      {
        pattern: /(01\d{13,14})(17.{12})(11.{12})(21.{1,20})/igm,
        groupCount: 4,
        fields: ["gtin", "expiredDate", "manufactureDate", "sn"]
      },

      //01 11* 17* 10    010761332705695211190926172109251019269AE2
      {
        pattern: /(01\d{13,14})(11\d{6})(17\d{6})(10.{1,20})/igm,
        groupCount: 4,
        fields: ["gtin", "manufactureDate", "expiredDate", "lot"]
      },

      //11190926172109251019269AE2
      {
        pattern: /(11\d{6})(17\d{6})(10.{1,20})/igm,
        groupCount: 3,
        fields: ["manufactureDate", "expiredDate", "lot"]
      },

      //HIBC   +J12369213895033611/$$012507a0150LP
      //
      {
        pattern: /([+][A-z]\d{17})[/][$][$][0](\S{4})(\S{6})[L]\S{1}/igm,
        groupCount: 3,
        fields: [ "hibc", "expiredDate",  "lot","LP"]
      },
      //01 17 11 21 (01)06901234567892(17)250505(11)220202(10)lot123(21)sn0001
      // {
      //   pattern: /(01\d{14})(17\d{6})(11\d{6})(10\S{6})(21.{1,20})/igm,
      //   groupCount: 5,
      //   fields: ["udi", "expiredDate","manufactureDate", "lot",  "sn"]
      // },
    ]
    let result = {}
    result = barcode.getUdiData(input)
    if (result != null) {
      return result
    }

    // 以下按照正则表达式解析
    result = {}
    let rulesUdi = barcode.getUdiRule()
    let rulesAll = [...rulesUdi, ...rules]
    //遍历模板
    for (let i = 0; i < rulesAll.length; i++) {
      let rule = rulesAll[i]
      //通过模板进行正则的匹配，获得最优解
      let matches = rule.pattern.exec(input)
      if (!matches) {
        continue
      }
      //因为得到的matches会包含字符串本身所以要+1
      if (matches.length != rule.groupCount + 1) {
        continue
      }
      console.log('gtinAnalysis使用规则rule', rule)
      //将获取到的结果存入result
      for (let j = 1; j < matches.length; j++) {
        let field = rule.fields[j - 1]
        result[field] = matches[j]
      }
      break
    }

    if (result.hibc) {
      let expiredDate = result.expiredDate
      let year = '20'+expiredDate.substring(2,4)
      let month = expiredDate.substring(0,2)
      result.expiredDate = year+'-'+ month + '-'+ '01' + ' 00:00:00'
      return result;
    }
    let results = Object.keys(result).forEach(objKey => {
      let data = result[objKey]
      if (data.startsWith("17") || data.startsWith("12")) {
        let year = data.substring(2, 4)
        let mouth = data.substring(4, 6)
        let day = data.substring(6, 8)
        if (day == "00") {
          if (mouth == "02") {
            if (year % 4 == 0) {
              day = "29"
            } else {
              day = "28"
            }
          } else if (mouth == "04" || mouth == "06" || mouth == "09" || mouth == "11") {
            day = "30"
          } else {
            day = "31"
          }
        }
        result[objKey] = data.substring(0, 2) + "20" + year + "-" + mouth + "-" + day
      }
      if (data.startsWith("11")) {
        let year = data.substring(2, 4)
        let mouth = data.substring(4, 6)
        let day = data.substring(6, 8)
        if (day == "00") {
          day = "01"
        }
        result[objKey] = data.substring(0, 2) + "20" + year + "-" + mouth + "-" + day
      }
    })
    Object.keys(result).forEach(objKey => {
      result[objKey] = result[objKey].substring(2)
    })
    return result
  },
  /***
   * @Author: Tai
   * @date: 2024/4/22
   * @Description:
   (01)产品标识DI (11)生产日期 (17)失效日期 (10)生产批号 (21)序列号
   fields: ["udi", "expiredDate","manufactureDate", "lot",  "sn"]
   01必须，之后的PI最少有一个
   */
  getUdiRule() {
    let rulesUdi = []
    let diRule = '(01\\d{14})'
    let diRuleMap = {
      name:'udi',
      value: '(01\d{14})'
    }
    // let piRuleList = ['(17\d{6})', '(11\d{6})', '(10\S{6})', '(21.{1,20})']
    let piRuleList = [
      {
        name:'manufactureDate',
        value: '(11\\d{6})'
      },
      {
        name:'expiredDate',
        value: '(17\\d{6})'
      },
      {
        name:'lot',
        value: '(10.{1,20})'
      },
      {
        name:'sn',
        value: '(21.{1,20})'
      }
    ]

    //DI + PI(4位)
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[0], piRuleList[1], piRuleList[2], piRuleList[3]]))

    //DI + PI(3位)
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[0], piRuleList[1], piRuleList[2]]))
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[0], piRuleList[2], piRuleList[3]]))
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[1], piRuleList[2], piRuleList[3]]))

    //DI + PI(2位)
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[0], piRuleList[1]]))
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[0], piRuleList[2]]))
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[0], piRuleList[3]]))
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[1], piRuleList[2]]))
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[1], piRuleList[3]]))
    rulesUdi = rulesUdi.concat(barcode.arrFullSort([piRuleList[2], piRuleList[3]]))
    //DI + PI(1位)
    let rulesUdiPi1 = []
    piRuleList.forEach((value,index) => {
      rulesUdiPi1.push([value])
    })
    rulesUdi = rulesUdi.concat(rulesUdiPi1)
    console.log('rulesUdi', rulesUdi)
    //构建正则表达式
    let rulesUdiReg = []
    rulesUdi.forEach((patList,index) => {
      let nameList = patList.map(item => {
        return item.name
      })
      nameList.unshift('udi')

      let valueList = patList.map(item => {
        return item.value
      })
      valueList.unshift(diRule)

      rulesUdiReg.push(
        {
          // pattern: /(01\d{14})(17\d{6})(11\d{6})(10\S{6})(21.{1,20})/igm,
          // pattern: new RegExp( valueList.join('') + '\/\/igm'),
          pattern: eval('/' + valueList.join('') + '/igm'),
          groupCount: valueList.length,
          fields: nameList,
          remark: 'udi'
        }
      )
    })

    //DI + PI(0位)
    rulesUdiReg.push(
      {
        // pattern: /(01\d{14})(17\d{6})(11\d{6})(10\S{6})(21.{1,20})/igm,
        // pattern: new RegExp('/' + diRule + '\/\/igm'),
        pattern: eval('/' + diRule + '/igm'),
        groupCount: 1,
        fields: ['udi'],
        remark: 'udi'
      }
    )

    console.log('rulesUdiReg', rulesUdiReg)

    return rulesUdiReg
  },

  /***
   * @Author: Tai
   * @date: 2024/4/22
   * @Description: 数组全排列
   * <pre>
   *    传入 1,2,3
   *    返回
   *      1,2,3
   *      1,3,2
   *      2,1,3
   *      2,3,1
   *      3,1,2
   *      3,2,1
   * </pre>
   */
  arrFullSort(arr) {
    if (arr.length == 1)
      return arr;
    else if (arr.length == 2)
      return [[arr[0],arr[1]],[arr[1],arr[0]]];
    else {
      var temp = [];
      for (var i = 0; i < arr.length; i++) {
        var save = arr[i];
        arr.splice(i, 1);//取出arr[i]
        var res = barcode.arrFullSort(arr);//递归排列arr[0],arr[1],...,arr[i-1],arr[i+1],...,arr[n]
        arr.splice(i, 0, save);//将arr[j]放入数组，保持原来的位置
        for (var j = 0; j < res.length; j++) {
          res[j].push(arr[i]);
          temp.push(res[j]);//将arr[j]组合起来
        }
      }
      return temp;
    }
  },

  /***
   * @param input 文本值
   *  以下格式
   *    (01)06901234567892(17)250505(11)220202(10)lot123(21)sn0001
   *    (01)06901234567892(17)250505
   *    (01)06902270010755(11)221111(17)261110(10)2210510(21)1029
   * @return:  解析后的数据对象
   * @Author: Tai
   * @date: 2024/5/9
   * @Description:  通过非正则表达式解析
   */
  getUdiData(input) {
    if (input == undefined) {
      return null
    }
    let udiDiHit = '(01)'
    // debugger
    // 没有主码的，忽略
    if (input.indexOf(udiDiHit) == -1)  {
      return null
    }

    let udiMap = {
      '01': {
        hit: udiDiHit,
        name: 'udi'
      },
      '11': {
        hit: '(11)',
        name: 'manufactureDate'
      },
      '17': {
        hit: '(17)',
        name: 'expiredDate'
      },
      '10': {
        hit: '(10)',
        name: 'lot'
      },
      '21': {
        hit: '(21)',
        name: 'sn'
      }
    }

    // 需要转换成年月日的字段
    let hitDateArr = ['11', '17']

    let result = {}
    let indexStart = -1
    let indexStartRight = -1
    let indexEnd = -1
    let inputRight = ''
    let value = ''
    let yearPre = (new Date().getFullYear() + '').substring(0, 2)
    Object.keys(udiMap).forEach(key => {
      let hitOb = udiMap[key]
      indexStart = input.indexOf(hitOb.hit)
      if (indexStart != -1) {
        //起止位置往右剩余的字符串
        inputRight = input.substring(indexStart + 4)
        //起止位置往右第一个左括号
        indexStartRight = inputRight.indexOf('(')
        if (indexStartRight == -1) {
          value = inputRight
        } else {
          value = inputRight.substring(0, indexStartRight)
        }

        // 需要转换成日期的， 原始格式为 年年月月日日 即 220202 将解析为 2022-02-02
        if (hitDateArr.includes(key)) {
          if (value.length == 6 ) {
            value = yearPre + '' + value.substring(0, 2) + '-' +  value.substring(2, 4)+ '-' +  value.substring(4, 6)
          } else if (value.length == 5 ) {
            value = yearPre + '' + value.substring(0, 2) + '-' +  value.substring(2, 4)+ '-0' +  value.substring(4, 5)
          } else{
            global.utilMessage.warning(`日期格式解析失败,日期: ${value}`)
            return true
          }
        }

        result[hitOb.name] = value
      }

    })
    return result
  }
}

//udi解析测试
// console.log('gtinAnalysis (01)06901234567892(17)250505(11)220202(10)lot123(21)sn0001', barcode.gtinAnalysis('(01)06901234567892(17)250505(11)220202(10)lot123(21)sn0001'))
// console.log('gtinAnalysis (01)06902270010755(11)221111(17)261110(10)2210510(21)1029', barcode.gtinAnalysis('(01)06902270010755(11)221111(17)261110(10)2210510(21)1029'))
// console.log('gtinAnalysis (01)06902270010755(11)221111', barcode.gtinAnalysis('(01)06902270010755(11)221111'))

export default barcode
